package com.songjg.demo.token;

import com.github.pagehelper.util.StringUtil;
import com.songjg.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author songjg
 */
@Service
@Slf4j
public class TokenServiceImpl implements TokenServie {
    private static final String TOKEN_PREFIX = "TOKEN:";
    private static final String TOKEN_NAME = "token";
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public String createToken() {
        String random = UUID.randomUUID().toString().replace("-", "");
        StringBuilder token = new StringBuilder();
        try {
            token.append(TOKEN_PREFIX).append(random);
            boolean setEx = redisUtil.setEx(token.toString(), token.toString(), 1000L);
            boolean notEmpty = StringUtil.isNotEmpty(token.toString());
            if (notEmpty && setEx) {
                return token.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(TOKEN_NAME);
        boolean empty = StringUtil.isEmpty(token);
        if (empty) {
            token = request.getParameter(TOKEN_NAME);
            if (StringUtil.isEmpty(token)) {
                throw new Exception("[request : token不存在！！！]");
            }
        }
        if (!redisUtil.exists(token)) {
            throw new Exception("[redis : token不存在！！！]");
        }
        boolean remove = redisUtil.remove(token);
        if (!remove) {
            throw new Exception("[redis : 删除token失败！！！]");
        }
        return true;
    }
}
